package com.ywjh.inter.conn;

import java.util.Date;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
import com.ywjh.inter.common.SystemConfig;

public class MemcacheConn {

	private static volatile MemcacheConn instance = null;

	private MemCachedClient memCachedClient = null;

	private static String ip = SystemConfig.MEMCACHED_IP;
	private static int port = SystemConfig.MEMCACHED_PORT;

	public static MemcacheConn getInstance() {
		if (instance == null) {
			synchronized (MemcacheConn.class) {
				if (instance == null) {
					instance = new MemcacheConn();
				}
			}
		}
		return instance;
	}

	private MemcacheConn() {
		String[] servers = { ip + ":" + port };
		SockIOPool pool = SockIOPool.getInstance();
		// 获取socke连接池的实例对象
		// 设置服务器信息
		pool.setServers(servers);
		// 设置初始连接数、最小和最大连接数以及最大处理时间
		pool.setInitConn(5);
		pool.setMinConn(5);
		pool.setMaxConn(250);
		pool.setMaxIdle(1000 * 60 * 60 * 6);
		// 设置主线程的睡眠时间
		pool.setMaintSleep(30);
		// 设置TCP的参数，连接超时等
		pool.setNagle(false);
		pool.setSocketTO(3000);
		pool.setSocketConnectTO(0);
		// 初始化连接池
		pool.initialize();
		memCachedClient = new MemCachedClient();
		System.out.println(ip + ":" + port);
	}

	public boolean put(String key, String value, Date time) {

		boolean b = false;
		try {

			b = memCachedClient.set(key, value, time);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}

	/**
	 * 
	 * @param key
	 * @param value
	 * @param time  单位：秒
	 * @return
	 */
	public boolean put(String key, String value, int time) {

		boolean b = false;
		try {

			b = memCachedClient.set(key, value, new Date(System.currentTimeMillis() + time * 1000l));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
	/**
	 * 
	 * @param key
	 * @param value
	 * @param time  单位：秒
	 * @return
	 */
	public boolean put(String key, String value, long time) {

		boolean b = false;
		try {

			b = memCachedClient.set(key, value, new Date(System.currentTimeMillis() + time * 1000l));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
	public boolean put(String key, String value) {

		boolean b = false;
		try {

			b = memCachedClient.set(key, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}

	public String get(String key) {
		Object result = "";
		try {
			result = memCachedClient.get(key);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		if (result != null) {
			return result.toString();
		}
		return null;

	}

	public boolean delete(String key) {
		return memCachedClient.delete(key);
	}

	/**
	 * resin shutdown的时候调用改方法
	 */
	public static void destroy() {

		if (instance != null) {
			SockIOPool.getInstance().shutDown();
			instance = null;
		}
	}
}
